package com.example.advancecomponents.adaptors;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.view.LayoutInflaterCompat;

import com.example.advancecomponents.R;
import com.example.advancecomponents.vo.Star;

import java.util.ArrayList;
import java.util.List;

public class CustomizedAdaptor extends BaseAdapter implements View.OnClickListener {

    private Context context;

    private final List<Star> stars;

    public CustomizedAdaptor(Context context, List<Star> stars) {
        this.context = context;

        this.stars = stars;
    }

    @Override
    public int getCount() {
        return stars.size();
    }

    @Override
    public Object getItem(int position) {
        return stars.get(position);
    }

    @Override
    public long getItemId(int position) {
        return stars.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Star star = stars.get(position);
        Holder holder;
        if (convertView == null) {
            holder = new Holder();
            convertView = LayoutInflater.from(context).inflate(R.layout.complex_view, null);
            holder.image = convertView.findViewById(R.id.icon);
            holder.title = convertView.findViewById(R.id.title);
            holder.detail = convertView.findViewById(R.id.detail);
            holder.goToButton = convertView.findViewById(R.id.goTo);

            convertView.setTag(holder);
        } else {
            Log.d("CustomizedAdaptor", "复用旧的视图，实现性能优化");

            holder = (Holder) convertView.getTag();
        }


        holder.image.setImageResource(star.getIcon());


        holder.title.setText(star.getName());


        holder.detail.setText(star.getDetail());

        holder.goToButton.setTag(star.getName());
        holder.goToButton.setOnClickListener(this);

        return convertView;
    }

    @Override
    public void onClick(View v) {
        Button button = (Button) v;
        Toast.makeText(context, "按钮点击了 " + button.getTag(), Toast.LENGTH_SHORT).show();
    }

    static class Holder {
        ImageView image;

        TextView title;

        TextView detail;

        Button goToButton;
    }
}
